#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QWindow>
#include <QDebug>
#include <unistd.h>
#include <sys/stat.h>
#include <iostream>
#include <QDir>
#include <fcntl.h>
#include <QDebug>
#include <QSettings>
#include <QQmlContext>
#include "processmanager.h"
#include "xatom-helper.h"

void qtVersionHandle()
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif

#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
    QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
#endif
}


// 单例文件锁
bool fileLock()
{
    QDir dir("/tmp/ukui-new-function-introduction/");
    if(dir.exists()) {
        QString lockPath = "/tmp/ukui-new-function-introduction/ukui-new-function-introduction.lock";
        umask(0000);
        int fd = open(lockPath.toUtf8().data(), O_RDWR | O_CREAT | O_TRUNC,0666);
        if (fd < 0) {
            qDebug()<<"单例文件锁打开异常";
            qDebug()<<"1";
            exit(0);
        }
        return lockf(fd, F_TLOCK, 0);
    } else {
        dir.mkdir("/tmp/ukui-new-function-introduction/");//只创建一级子目录，即必须保证上级目录存在
        chmod("/tmp/ukui-new-function-introduction/",0777);
        QString lockPath = "/tmp/ukui-new-function-introduction/ukui-new-function-introduction.lock";
        umask(0000);
        int fd = open(lockPath.toUtf8().data(), O_RDWR | O_CREAT | O_TRUNC,0666);
        if (fd < 0) {
            qDebug()<<"单例文件锁打开异常";
            exit(0);
        }
        return lockf(fd, F_TLOCK, 0);
    }
}

// 启动检测配置文件
bool readStartConf()
{
    int rebootNum;
    QFileInfo file(QDir::homePath() +"/.config/ukui/ukui-new-function-introduction.conf");
    if(file.isFile()) {
        QSettings *qsetting = new QSettings(QDir::homePath() +"/.config/ukui/ukui-new-function-introduction.conf",QSettings::IniFormat);
        rebootNum = qsetting->value("startupnum").toInt() + 1;
        qsetting->setValue("startupnum",rebootNum);
    } else {
        QSettings *qsetting = new QSettings(QDir::homePath() +"/.config/ukui/ukui-new-function-introduction.conf",QSettings::IniFormat);
        qsetting->setValue("startupnum",1);
        rebootNum = qsetting->value("startupnum").toInt();
    }
    if (rebootNum < 2) {
        return true;
    } else {
        return false;
    }
}

int main(int argc, char *argv[])
{
    QString arg = QString::fromUtf8(argv[1]);
    qtVersionHandle();

    if (!fileLock()) {
        if (arg == "-nocheck") {
            qDebug()<<"不用检查";
            QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

            QGuiApplication app(argc, argv);
            qmlRegisterType<processmanager>("org.lyd", 1, 0, "ProcessManager");
            qRegisterMetaType<processmanager*>("p*");


            QQmlApplicationEngine engine;
            const QUrl url(QStringLiteral("qrc:/main.qml"));
            QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                             &app, [url](QObject *obj, const QUrl &objUrl) {
                if (!obj && url == objUrl)
                    QCoreApplication::exit(-1);
            }, Qt::QueuedConnection);
            engine.load(url);
            engine.rootContext()->setContextProperty("p", new processmanager());

            MotifWmHints hints;
            hints.flags = MWM_HINTS_FUNCTIONS|MWM_HINTS_DECORATIONS;
            hints.functions = MWM_FUNC_ALL;
            hints.decorations = MWM_DECOR_BORDER;
            XAtomHelper::getInstance()->setWindowMotifHint(qobject_cast<QWindow*>(engine.rootObjects().first())->winId(), hints);

            return app.exec();
        } else {
            if (readStartConf()) {
                QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

                QGuiApplication app(argc, argv);
                qmlRegisterType<processmanager>("org.lyd", 1, 0, "ProcessManager");
                qRegisterMetaType<processmanager*>("p*");

                QQmlApplicationEngine engine;
                const QUrl url(QStringLiteral("qrc:/main.qml"));
                QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                                 &app, [url](QObject *obj, const QUrl &objUrl) {
                    if (!obj && url == objUrl)
                        QCoreApplication::exit(-1);
                }, Qt::QueuedConnection);
                engine.load(url);
                engine.rootContext()->setContextProperty("p", new processmanager());

                MotifWmHints hints;
                hints.flags = MWM_HINTS_FUNCTIONS|MWM_HINTS_DECORATIONS;
                hints.functions = MWM_FUNC_ALL;
                hints.decorations = MWM_DECOR_BORDER;
                XAtomHelper::getInstance()->setWindowMotifHint(qobject_cast<QWindow*>(engine.rootObjects().first())->winId(), hints);

                return app.exec();
            } else {
                qDebug()<<"The demo program has been started. If you want to start it again, please execute [ ukui-new-function-introduction -nocheck] ";
                return 0;
            }
        }

    } else {
        qDebug()<< "ukui-new-function-introduction is running";
    }
}
